package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * stack
 * 1541. 平衡括号字符串的最少插入次数
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/6 22:50
 */
public class MinInsertions {


    public static void main(String[] args) {
        MinInsertions test = new MinInsertions();

        // 0
//        String str = "())(())))";
        // 1
        String str = "(()))";
//        String str = "))())(";
        // 12
//        String str = "((((((";
        // 5
//        String str = ")))))))";
        // 4
//        String str = "(()))(()))()())))";

        int i = test.minInsertions(str);
        System.out.println(i);
    }

    public int minInsertions(String s) {
        int count = 0;
        Stack<Character> stack = new Stack<>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == '(') {
                if (!stack.isEmpty() && stack.peek() == ')') {
                    stack.pop();
                    if (stack.isEmpty()) {
                        count += 2;
                    } else {
                        stack.pop();
                        count++;
                    }
                }
                stack.add(c);
            } else {
                if (stack.isEmpty()) {
                    stack.add(c);
                } else {
                    if (stack.peek() == ')') {
                        stack.pop();
                        if (stack.isEmpty()) {
                            count++;

                        } else {
                            stack.pop();
                        }
                    } else {
                        stack.add(c);
                    }
                }
            }
        }
        while (!stack.isEmpty()) {
            Character pop = stack.pop();
            if (pop == '(') {
                count += 2;
            } else {
                if (!stack.isEmpty()) {
                    stack.pop();
                    count++;
                } else {
                    count += 2;
                }
            }
        }
        return count;
    }

}
